<template>
  <div class="script-manage-container">
    <!-- 加载中状态 -->
    <el-skeleton :loading="loading" animated>
      <template #template>
        <el-skeleton-item variant="h1" style="width: 40%" />
        <el-skeleton-item variant="text" style="margin-top: 20px" />
      </template>

      <template #default>
        <!-- 未注册店铺 -->
        <div v-if="!isShop" class="not-shop">
          <el-empty description="您还不是店铺">
            <el-button type="primary" @click="handleRegisterShop">
              注册成为店铺
            </el-button>
          </el-empty>
        </div>

        <!-- 已注册店铺 - 显示剧本列表 -->
        <div v-else class="shop-content">
          <div class="header">
            <h2>剧本管理</h2>
            <el-button type="success" @click="handleBuyScript">
              <el-icon><ShoppingCart /></el-icon>
              购买剧本
            </el-button>
          </div>

          <!-- 剧本列表 -->
          <el-table :data="scriptList" border style="width: 100%" v-loading="tableLoading">
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="title" label="剧本名称" min-width="150" />
            <el-table-column prop="author" label="作者" width="120" />
            <el-table-column prop="price" label="价格" width="100">
              <template #default="{ row }">
                ¥{{ row.price }}
              </template>
            </el-table-column>
            <el-table-column prop="sold" label="销量" width="100" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="expireTime" label="到期时间" width="180">
              <template #default="{ row }">
                {{ row.expireTime || '永久' }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="{ row }">
                <el-button link type="primary" size="small" @click="handleDetail(row)">
                  查看详情
                </el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 空状态 -->
          <el-empty v-if="scriptList.length === 0 && !tableLoading" description="暂无剧本数据，请前往商城购买" />
        </div>
      </template>
    </el-skeleton>

    <!-- 剧本详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="剧本详情"
      width="800px"
      :close-on-click-modal="false"
    >
      <div class="script-detail">
        <div v-if="currentScript" class="detail-content">
          <!-- 剧本封面和基本信息 -->
          <div class="detail-header">
            <div class="detail-cover">
              <img
                :src="`${BASE_IMAGE_URL}/${currentScript.contentFile}`"
                :alt="currentScript.title"
                @error="handleImageError"
              />
            </div>
            <div class="detail-basic-info">
              <h2 class="detail-title">{{ currentScript.title }}</h2>
              <div class="info-item">
                <span class="info-label">作者：</span>
                <span class="info-value">{{ currentScript.author }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">出版社：</span>
                <span class="info-value">{{ currentScript.publishName || '未设置' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">出版日期：</span>
                <span class="info-value">{{ currentScript.publishDate || '未设置' }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">分类：</span>
                <span class="info-value">{{ getCategoryName(currentScript.categoryId) }}</span>
              </div>
              <div class="info-item">
                <span class="info-label">状态：</span>
                <el-tag :type="getStatusType(currentScript.status)">
                  {{ getStatusText(currentScript.status) }}
                </el-tag>
              </div>
              <div class="info-item">
                <span class="info-label">已售：</span>
                <span class="info-value">{{ currentScript.sold || 0 }} 份</span>
              </div>
              <div class="info-item">
                <span class="info-label">使用天数：</span>
                <span class="info-value">{{ currentScript.usageDays || '未设置' }} 天</span>
              </div>
              <div class="info-item">
                <span class="info-label">到期时间：</span>
                <span class="info-value">{{ currentScript.expireTime || '永久' }}</span>
              </div>
              <div class="info-item price-item">
                <span class="info-label">价格：</span>
                <span class="price-value">¥{{ currentScript.price }}</span>
              </div>
            </div>
          </div>

          <!-- 剧本简介 -->
          <div class="detail-description">
            <h3 class="section-title">剧本简介</h3>
            <p class="description-text">{{ currentScript.description || '暂无简介' }}</p>
          </div>
        </div>
      </div>

      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { getShopByUserIdAPI } from '@/api/shop'
import { getScriptListAPI } from '@/api/script'
import { ElMessage } from 'element-plus'
import { ShoppingCart } from '@element-plus/icons-vue'
import type { Script } from '@/types/script'

const BASE_IMAGE_URL = import.meta.env.VITE_API_BASE_URL

// 店铺信息类型
interface ShopInfo {
  id: number
  name: string
  phone: string
  email: string
  status: number
  [key: string]: unknown
}

const router = useRouter()

const loading = ref(true)
const tableLoading = ref(false)
const isShop = ref(false)
const shopInfo = ref<ShopInfo | null>(null)
const scriptList = ref<Script[]>([])

// 详情对话框相关
const detailVisible = ref(false)
const currentScript = ref<Script | null>(null)

// 分类列表
const categories = [
  { id: 1, name: '剧情类' },
  { id: 2, name: '喜剧类' },
  { id: 3, name: '悬疑类' },
  { id: 4, name: '历史类' },
  { id: 5, name: '科幻类' }
]

// 检查是否是店铺
const checkShop = async () => {
  loading.value = true
  try {
    const { data: res } = await getShopByUserIdAPI()
    console.log('店铺查询结果：', res)
    // 如果 res.data 不为 null，说明是店铺
    if (res.code === 1 && res.data !== null) {
      isShop.value = true
      shopInfo.value = res.data
      // 如果是店铺，获取剧本列表
      await getScriptList()
    } else {
      isShop.value = false
    }
  } catch (error) {
    console.log('不是店铺或查询失败', error)
    isShop.value = false
  } finally {
    loading.value = false
  }
}

// 获取剧本列表
const getScriptList = async () => {
  tableLoading.value = true
  try {
    const { data: res } = await getScriptListAPI()
    console.log('剧本列表原始数据：', res)
    if (res.code === 1) {
      // 使用店铺ID过滤剧本
      const shopId = shopInfo.value?.id
      console.log('当前店铺ID：', shopId, '类型：', typeof shopId)

      if (shopId) {
        // 先看看所有剧本的 shopId
        console.log('所有剧本的shopId：', res.data.map((s: Script) => ({
          id: s.id,
          title: s.title,
          shopId: s.shopId,
          shopIdType: typeof s.shopId
        })))

        // 转换为字符串比较
        const filtered = res.data.filter((script: Script) => {
          const match = String(script.shopId) === String(shopId)
          console.log(`剧本${script.id}的shopId: ${script.shopId}(${typeof script.shopId}), 当前店铺: ${shopId}(${typeof shopId}), 匹配: ${match}`)
          return match
        })

        scriptList.value = filtered
        console.log('过滤后的剧本列表：', scriptList.value)

        // 如果过滤后为空，显示所有剧本（临时调试）
        if (filtered.length === 0) {
          console.warn('过滤后没有剧本，暂时显示所有剧本')
          scriptList.value = res.data
        }
      }
    } else {
      ElMessage.error(res.msg || '获取剧本列表失败')
    }
  } catch (error) {
    console.error('获取剧本列表失败', error)
    ElMessage.error('获取剧本列表失败')
  } finally {
    tableLoading.value = false
  }
}

// 注册成为店铺
const handleRegisterShop = () => {
  router.push('/shop/register')
}

// 购买剧本
const handleBuyScript = () => {
  router.push('/mall')
}

// 查看详情
const handleDetail = (row: Script) => {
  currentScript.value = row
  console.log('当前剧本：', currentScript.value)
  detailVisible.value = true
}

// 获取分类名称
const getCategoryName = (categoryId: number) => {
  const category = categories.find(cat => cat.id === categoryId)
  return category?.name || '未知分类'
}

// 图片加载失败处理
const handleImageError = (e: Event) => {
  const target = e.target as HTMLImageElement
  target.src = 'https://lvyou-1332935562.cos.ap-nanjing.myqcloud.com/ceshi/IMG_1351.PNG'
}

// 获取状态类型
const getStatusType = (status: number) => {
  const typeMap: Record<number, string> = {
    0: 'info',
    1: 'success',
    2: 'warning',
    3: 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status: number) => {
  const textMap: Record<number, string> = {
    0: '待审核',
    1: '已发布',
    2: '审核中',
    3: '已下架'
  }
  return textMap[status] || '未知'
}

onMounted(() => {
  checkShop()
})
</script>

<style scoped>
.script-manage-container {
  padding: 20px;
}

.not-shop {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
}

.shop-content {
  width: 100%;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

/* 剧本详情样式 */
.script-detail {
  min-height: 400px;
}

.detail-content {
  padding: 10px 0;
}

.detail-header {
  display: flex;
  gap: 30px;
  margin-bottom: 30px;
  padding-bottom: 30px;
  border-bottom: 1px solid #ebeef5;
}

.detail-cover {
  width: 200px;
  flex-shrink: 0;
}

.detail-cover img {
  width: 100%;
  height: 280px;
  object-fit: cover;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.detail-basic-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.detail-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 10px 0;
  line-height: 1.4;
}

.info-item {
  display: flex;
  align-items: center;
  font-size: 14px;
  line-height: 1.6;
}

.info-label {
  color: #909399;
  min-width: 80px;
}

.info-value {
  color: #606266;
  flex: 1;
}

.price-item {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #f0f0f0;
}

.price-value {
  font-size: 28px;
  font-weight: 600;
  color: #f56c6c;
}

.detail-description {
  margin-top: 20px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin: 0 0 16px 0;
  padding-bottom: 10px;
  border-bottom: 2px solid #409eff;
}

.description-text {
  font-size: 14px;
  color: #606266;
  line-height: 1.8;
  margin: 0;
  white-space: pre-wrap;
  word-break: break-word;
}

/* 详情对话框响应式 */
@media (max-width: 768px) {
  .detail-header {
    flex-direction: column;
    align-items: center;
  }

  .detail-cover {
    width: 160px;
  }

  .detail-cover img {
    height: 224px;
  }

  .detail-title {
    font-size: 20px;
  }

  .price-value {
    font-size: 24px;
  }
}
</style>
